package com.jrx.anytxn.investor.timer.job.transfer.step;

import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.InternetUtils;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.feign.gateway.bean.AcctInfo;
import com.jrx.anytxn.feign.gateway.bean.ApiResponse;
import com.jrx.anytxn.feign.gateway.request.CoreRequest04;
import com.jrx.anytxn.feign.gateway.response.CoreResponse04;
import com.jrx.anytxn.feign.gateway.service.IInnerGatewayService;
import com.jrx.anytxn.investor.constant.TransBizConstant;
import com.jrx.anytxn.investor.entity.TlFundTransferDetail;
import com.jrx.anytxn.investor.entity.TlFundTransferLog;
import com.jrx.anytxn.investor.mapper.ext.ExtTlFundTransferDetailMapper;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 转账 - processor
 *
 * @author jing.xy
 */
@Service
public class TransferProcessor implements ItemProcessor<TlFundTransferLog, TlFundTransferLog> {

    Logger logger = LoggerFactory.getLogger(TransferProcessor.class);


    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ExtTlFundTransferDetailMapper extTlFundTransferDetailMapper;
    @Lazy
    @Autowired
    private IInnerGatewayService innerGatewayService;


    @Override
    public TlFundTransferLog process(TlFundTransferLog log) throws Exception {
        PrOrganizationTable organization = organizationTableService.findByOrId(log.getOrganizationId(), log.getTenantId());
        Date businessDate = organization.getNextProcessingDate();//机构上 当天日期

        TlFundTransferLog updateLog = new TlFundTransferLog();
        updateLog.setId(log.getId());
        updateLog.setCustomerId(log.getCustomerId());
        updateLog.setTenantId(log.getTenantId());
        updateLog.setLaunchTime(DateUtils.getBusinessTime(new Date(), businessDate));



        CoreRequest04 req = new CoreRequest04();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID); // 请求系统Id
        req.setServiceIp(InternetUtils.getLocalIp()); // 请求ip地址
        req.setTenantId(log.getTenantId()); // 租户Id
        req.setServiceSeq(log.getRefNo()); // 请求流水号
        req.setCcy(TransBizConstant.CURRENCY_CNY); // 币种

        List<TlFundTransferDetail> detailList = extTlFundTransferDetailMapper.selectByTransferSeqNo(log.getSeqNo());
        List<AcctInfo> acctList = detailList.stream().map(detail ->
             new AcctInfo(detail.getAcctNo(),detail.getCrDrInd(),log.getAmount().toPlainString(),detail.getNarrative(),null)
        ).collect(Collectors.toList());
        req.setAcctList(acctList);

        ApiResponse<CoreResponse04> resp = innerGatewayService.transferAcct(JsonUtils.toJSon(req));
        if (resp==null || TransBizConstant.GATEWAY_SUC!=resp.getCode()) {
            logger.error("订单[{}],资金清分异常：{}",log.getLoanId(), JsonUtils.toJSon(resp));
            throw new TxnBizException("资金清分异常");
        }
        Date completeDate = DateUtils.getBusinessTime(new Date(), businessDate);
        updateLog.setCompleteTime(completeDate);

        if (TransBizConstant.DEAL_RESULT_S.equals(resp.getData().getDealResult())) { //成功
            updateLog.setSumStatus(TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S);
        } else  {//失败
            updateLog.setSumStatus(TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_F);
        }

        return updateLog;
    }
}
